package com.lagou.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.lagou.bean.UpLoadResult;
import com.lagou.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;
@Service
public class FileUpLoadService {
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient  ossClient;
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".jpg",".jpeg",".png"};
    public UpLoadResult  upload(MultipartFile multipartFile){
        // 校验图片格式
        boolean  isLegal = false;
        for (String type:IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }
        UpLoadResult upLoadResult = new UpLoadResult();
        if (!isLegal){
            upLoadResult.setStatus("error");
            return  upLoadResult;
        }
        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return  upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix()+filePath);
        upLoadResult.setUid(filePath);
        return  upLoadResult;
    }

    public OSSObject download(String objectName){
        OSSObject object=null;
        boolean exist = ossClient.doesObjectExist(aliyunConfig.getBucketName(), objectName);
        if(exist){ //存在才获取
            object= ossClient.getObject(aliyunConfig.getBucketName(), objectName);
        }
        return object;
    }

    public boolean delete(String objectName){
        boolean exist = ossClient.doesObjectExist(aliyunConfig.getBucketName(), objectName);
        if(exist){
            ossClient.deleteObject(aliyunConfig.getBucketName(),objectName);
            return true;
        }else{
            return false;
        }
    }


    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
